var db = require('../database/db')

var schema = {
    "items": [
        "id", "name", "unit", "price", "qty", "desc"
    ],
    "announce": [
        "id", "title", "date", "body"
    ],
    "events": [
        "id", "title", "date", "body"
    ],
    "motd": [
        "id", "title", "body"
    ]
}

function readTable(table, cb) {
    let sql = `select * from ${table};`
    let data = {}
    db.all(sql, function(err, rows) {
        if(err) {
            throw err
        }
        rows.forEach(function(row) {
            data[row.id] = {}
            Object.keys(row).forEach(function(k) {
                data[row.id][k] = unescape(row[k])
            })
        })
        cb(data)
    })
}
function createRow(table, cb) {
    let sql = `insert into ${table} default values;`
    db.run(sql, cb)
}

function updateRow(table, rb, cb) {
    var pairs = ""
    for (field of schema[table].slice(1)) {
        //除了id这一列之外
        if (pairs) {
            pairs += ", "
        }
        pairs += `${field} = '${escape(rb[field])}'`
    }
    let sql = `update ${table} set ${pairs} where id = ?;`
    db.run(sql, rb['id'], cb)
}

function deleteRow(table, id, cb) {
    let sql = `delete from ${table} where id = ${id};`
    db.run(sql, cb)
}

module.exports = {
    schema,
    readTable,
    createRow,
    updateRow,
    deleteRow
}
